<template>
  <view class="container">
    <!-- 使用 uview-plus 的导航栏 -->
    <u-navbar
      :safeAreaInsetTop="true"
      :fixed="true"
      leftIcon="arrow-left"
      leftIconColor="#333333"
      :autoBack="false"
      @leftClick="goBack"
      :title="pageTitle"
      bgColor="#ffffff"
    ></u-navbar>

    <!-- 筛选栏 -->
    <view class="filter-bar" :style="{ top: (statusBarHeight + 140) + 'rpx' }">
      <view class="filter-list">
        <view class="filter-item" :class="{ active: activeFilter === 'category' }" @click="toggleFilter('category')">
          <text>{{ selectedCategory }}</text>
          <image class="filter-arrow" :class="{ rotate: activeFilter === 'category' }" src="/static/o2o/icon-xia@2x.png"></image>
        </view>
        <view class="filter-item" :class="{ active: activeFilter === 'area' }" @click="toggleFilter('area')">
          <text>{{ selectedArea }}</text>
          <image class="filter-arrow" :class="{ rotate: activeFilter === 'area' }" src="/static/o2o/icon-xia@2x.png"></image>
        </view>
        <view class="filter-item" :class="{ active: activeFilter === 'sort' }" @click="toggleFilter('sort')">
          <text>{{ selectedSort }}</text>
          <image class="filter-arrow" :class="{ rotate: activeFilter === 'sort' }" src="/static/o2o/icon-xia@2x.png"></image>
        </view>
        <view class="filter-item" :class="{ active: activeFilter === 'screen' }" @click="toggleFilter('screen')">
          <text>筛选</text>
          <image class="filter-icon" src="/static/o2o/icon-sx@2x.png"></image>
        </view>
      </view>

      <!-- 分类下拉 -->
      <view v-if="activeFilter === 'category'" class="dropdown-panel category-panel">
        <view class="category-list">
          <view 
            v-for="item in categoryList" 
            :key="item.id" 
            class="category-item" 
            :class="{ active: selectedCategoryId === item.id }"
            @click="selectCategory(item)"
          >
            <text>{{ item.name }}</text>
            <image v-if="selectedCategoryId === item.id" class="check-icon" src="/static/o2o/jt_you@2x.png"></image>
          </view>
        </view>
      </view>

      <!-- 附近下拉 -->
      <view v-if="activeFilter === 'area'" class="dropdown-panel area-panel">
        <view class="area-list">
          <view 
            v-for="item in areaList" 
            :key="item.id" 
            class="area-item" 
            :class="{ active: selectedAreaId === item.id }"
            @click="selectArea(item)"
          >
            <text>{{ item.region_name }}</text>
          </view>
        </view>
      </view>

      <!-- 排序下拉 -->
      <view v-if="activeFilter === 'sort'" class="dropdown-panel sort-panel">
        <view class="sort-list">
          <view 
            v-for="item in sortList" 
            :key="item.id" 
            class="sort-item" 
            :class="{ active: selectedSortId === item.id }"
            @click="selectSort(item)"
          >
            <text>{{ item.name }}</text>
          </view>
        </view>
      </view>

      <!-- 筛选下拉 -->
      <view v-if="activeFilter === 'screen'" class="dropdown-panel screen-panel">
        <view class="screen-content">
          <view class="screen-options">
            <view 
              class="screen-option" 
              :class="{ active: screenOptions.needReserv }"
              @click="toggleScreenOption('needReserv')"
            >
              只看免预约
            </view>
            <view 
              class="screen-option" 
              :class="{ active: screenOptions.holidayUsable }"
              @click="toggleScreenOption('holidayUsable')"
            >
              节假日可用
            </view>
            <view 
              class="screen-option" 
              :class="{ active: screenOptions.weekendUsable }"
              @click="toggleScreenOption('weekendUsable')"
            >
              周六日可用
            </view>
          </view>
          <view class="screen-buttons">
            <view class="reset-btn" @click="resetScreen">重置</view>
            <view class="confirm-btn" @click="confirmScreen">完成</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 遮罩层 -->
    <view v-if="activeFilter" class="mask" :style="{ top: (statusBarHeight + 188) + 'rpx' }" @click="closeFilter"></view>

    <!-- 商家列表 -->
    <scroll-view 
      class="merchant-list" 
      :style="{ marginTop: (statusBarHeight + 188) + 'rpx', height: 'calc(100vh - ' + (statusBarHeight + 188) + 'rpx)' }"
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      @refresherrefresh="onRefresh"
      :refresher-triggered="refreshing"
    >
      <view class="list-content">
        <view v-for="merchant in merchantList" :key="merchant.store ? merchant.store.store_id : merchant.id" class="merchant-item">
          <view class="merchant-info" @click="goToMerchant(merchant.store ? merchant.store.store_id : merchant.id)">
            <view class="merchant-logo">
              <image :src="merchant.store ? merchant.store.logo_image : merchant.logo_image" class="logo-img" mode="aspectFill"></image>
            </view>
            <view class="merchant-details">
              <view class="merchant-name">{{ merchant.store ? merchant.store.store_name : merchant.store_name }}</view>
              <view class="merchant-rating" v-if="merchant.store ? merchant.store.eval_score : merchant.eval_score">
                <up-rate 
                  :value="merchant.store ? merchant.store.eval_score : merchant.eval_score" 
                  :readonly="true" 
                  :size="12"
                  active-color="#ffca3e"
                  inactive-color="#c0c0c0"
                ></up-rate>
              </view>
              <view class="merchant-address">{{ merchant.store ? merchant.store.address : merchant.address }}</view>
            </view>
          </view>
          
          <!-- 商品列表 -->
          <view class="goods-list" v-if="merchant.goods_list && merchant.goods_list.length > 0">
            <view 
              v-for="(goods, index) in merchant.goods_list" 
              :key="goods.group_id || goods.id"
              v-show="index < 2 || merchant.showAll"
              class="goods-item"
              @click="goToGoods(goods.group_id || goods.id, goods.store_id)"
            >
              <view class="goods-info">
                <view class="goods-name">
                  {{ goods.title || goods.name }}{{ goods.need_resv == 1 ? '（需电话预约）' : '' }}
                </view>
                <view class="goods-sold">已售<text class="sold-num">{{ goods.sold_num || 0 }}</text></view>
              </view>
              <view class="goods-price-info">
                <view class="goods-price">￥{{ goods.price || '0.00' }}</view>
                <view class="goods-rebate">分润<text class="rebate-price">￥{{ goods.rebate_price || '0.00' }}</text></view>
              </view>
            </view>
          </view>

          <!-- 查看更多按钮 -->
          <view 
            v-if="merchant.goods_list && merchant.goods_list.length > 2" 
            class="view-more" 
            @click="toggleMerchantGoods(merchant)"
          >
            <text>{{ merchant.showAll ? '收起' : '查看更多优惠项目' }}</text>
            <image 
              class="more-arrow" 
              :class="{ rotate: merchant.showAll }"
              src="/static/o2o/youjiantou@2x.png"
            ></image>
          </view>
          
          <!-- 暂无商品 -->
          <view v-if="!merchant.goods_list || merchant.goods_list.length === 0" class="no-goods">
            <text>暂无优惠项目</text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading || loadStatus !== 'more'" class="loading">
          <up-loadmore :status="loadStatus"></up-loadmore>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && merchantList.length === 0" class="empty-state">
          <image src="/static/icons/empty-state.svg" class="empty-icon"></image>
          <text class="empty-text">暂无符合条件的商家信息</text>
          <text class="empty-tips">您可以尝试更换筛选条件或切换分类</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import * as api from '@/api/index.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      pageTitle: '生活服务',
      activeFilter: '',
      
      // 分类相关
      categoryList: [],
      selectedCategory: '全部分类',
      selectedCategoryId: 0,
      parentCateId: 34, // 默认美食分类ID
      
      // 区域相关
      areaList: [],
      selectedArea: '附近',
      selectedAreaId: 0,
      
      // 排序相关
      sortList: [
        { id: 1, name: '智能排序' },
        { id: 2, name: '分润最高' },
        { id: 3, name: '好评优先' },
        { id: 4, name: '人气最高' },
        { id: 5, name: '离我最近' }
      ],
      selectedSort: '智能排序',
      selectedSortId: 1,
      
      // 筛选相关
      screenOptions: {
        needReserv: false,
        holidayUsable: false,
        weekendUsable: false
      },
      
      // 商家列表
      merchantList: [],
      currentPage: 1,
      loading: false,
      loadStatus: 'more',
      refreshing: false,
      
      // 位置信息
      cityName: '北京',
      latitude: 39.915,
      longitude: 116.404
    }
  },
  
  onLoad(options) {
    this.initPage(options)
    this.getSystemInfo()
  },

  methods: {
    // 初始化页面
    async initPage(options) {
      // 先获取位置信息
      await this.getLocation()
      
      if (options.cate_id) {
        this.parentCateId = parseInt(options.cate_id)
        // 同时获取分类和区域数据
        await Promise.all([
          this.getCategoryChildren(options.cate_id),
          this.getAreaList()
        ])
      } else {
        this.loadInitialData()
      }
    },
    
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },
    
    // 加载初始数据
    async loadInitialData() {
      await Promise.all([
        this.getCategoryChildren(1), // 获取美食分类的子分类
        this.getAreaList()
      ])
      // 确保分类和区域数据加载完成后再获取商家列表
      if (this.categoryList.length === 0) {
        await this.getMerchantList()
      }
    },
    
    // 获取分类子级数据
    async getCategoryChildren(parentId) {
      try {
        const response = await api.o2oApi.getCateChild({
          cate_id: parentId
        })
        
        if (response.r === 0) {
          // 添加"全部分类"选项到列表开头
          this.categoryList = [{ id: 0, name: '全部分类' }, ...(response.data.list || [])]
          // 获取商家列表
          await this.getMerchantList()
        } else {
          console.error('获取分类子级失败:', response.msg)
          this.categoryList = [{ id: 0, name: '全部分类' }]
        }
      } catch (error) {
        console.error('获取分类子级异常:', error)
        this.categoryList = [{ id: 0, name: '全部分类' }]
      }
    },
    
    // 获取区域列表
    async getAreaList() {
      try {
        // 获取当前位置信息
        await this.getLocation()
        
        const response = await api.o2oApi.getVicinity({
          city_name: this.cityName
        })
        
        if (response.r === 0) {
          // 添加"附近"选项到列表开头
          this.areaList = [{ id: 0, region_name: '附近' }, ...response.data.list]
        } else {
          console.error('获取区域数据失败:', response.msg)
        }
      } catch (error) {
        console.error('获取区域数据失败:', error)
      }
    },
    
    // 获取位置信息
    async getLocation() {
      try {
        const location = uni.getStorageSync('location')
        if (location) {
          this.cityName = location.city || '北京市'
          this.latitude = location.latitude || 39.73280507586633
          this.longitude = location.longitude || 116.34809700859113
        } else {
          // 默认位置信息
          this.cityName = '北京市'
          this.latitude = 39.73280507586633
          this.longitude = 116.34809700859113
        }
      } catch (error) {
        console.error('获取位置信息失败:', error)
        // 默认位置信息
        this.cityName = '北京市'
        this.latitude = 39.73280507586633
        this.longitude = 116.34809700859113
      }
    },
    
    // 获取商家列表
    async getMerchantList(isLoadMore = false) {
      if (this.loading) return
      
      this.loading = true
      if (!isLoadMore) {
        this.currentPage = 1
        this.merchantList = []
      }
      
      try {
        // 确保位置信息已获取
        if (!this.latitude || !this.longitude) {
          await this.getLocation()
        }
        
        const params = {
          page: this.currentPage,
          cate_id: this.selectedCategoryId || 245, // 默认分类ID
          region_id: this.selectedAreaId,
          sort_type: this.selectedSortId,
          city_name: this.cityName,
          latitude: this.latitude,
          longitude: this.longitude
        }
        
        // 添加筛选条件
        if (this.screenOptions.needReserv) {
          params.need_resv = 1
        }
        if (this.screenOptions.holidayUsable) {
          params.holiday_usable = 1
        }
        if (this.screenOptions.weekendUsable) {
          params.weekend_usable = 1
        }
        
        const response = await api.o2oApi.getGoodsListForLife(params)
        
        if (response.r === 0) {
          const newList = response.data.list || []
          
          // 为每个商家添加显示状态
          newList.forEach(merchant => {
            merchant.showAll = false
          })
          
          if (isLoadMore) {
            this.merchantList = [...this.merchantList, ...newList]
          } else {
            this.merchantList = newList
          }
          
          this.loadStatus = newList.length < 10 ? 'noMore' : 'more'
          this.currentPage++
        } else {
          uni.showToast({
            title: response.msg || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取商家列表失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
          this.loading = false
          this.refreshing = false
        }
      },
      
      // 切换筛选项
      toggleFilter(type) {
      if (this.activeFilter === type) {
        this.activeFilter = ''
      } else {
        this.activeFilter = type
      }
    },
    
    // 关闭筛选
    closeFilter() {
      this.activeFilter = ''
    },
    
    // 选择分类
    selectCategory(item) {
      this.selectedCategory = item.name
      this.selectedCategoryId = item.id
      this.activeFilter = ''
      this.getMerchantList()
    },
    
    // 选择区域
    selectArea(item) {
      this.selectedArea = item.region_name
      this.selectedAreaId = item.id
      this.activeFilter = ''
      this.getMerchantList()
    },
    
    // 选择排序
    selectSort(item) {
      this.selectedSort = item.name
      this.selectedSortId = item.id
      this.activeFilter = ''
      this.getMerchantList()
    },
    
    // 切换筛选选项
    toggleScreenOption(key) {
      this.screenOptions[key] = !this.screenOptions[key]
    },
    
    // 重置筛选
    resetScreen() {
      this.screenOptions = {
        needReserv: false,
        holidayUsable: false,
        weekendUsable: false
      }
    },
    
    // 确认筛选
    confirmScreen() {
      this.activeFilter = ''
      this.getMerchantList()
    },
    
    // 切换商家商品显示
    toggleMerchantGoods(merchant) {
      merchant.showAll = !merchant.showAll
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.getMerchantList()
    },
    
    // 加载更多
    loadMore() {
      if (this.loadStatus === 'more') {
        this.getMerchantList(true)
      }
    },
    
    // 返回
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转商家详情
    goToMerchant(storeId) {
      uni.navigateTo({
        url: `/pages/o2o/merchant-detail?id=${storeId}`
      })
    },
    
    // 跳转商品详情
    goToGoods(groupId, storeId) {
      uni.navigateTo({
        url: `/pages/o2o/goods-detail?group_id=${groupId}&store_id=${storeId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #eee;
}

/* 自定义导航栏 */
.u-navbar {
  z-index: 999;
}

.u-navbar__content {
  background-color: #ffffff !important;
}

/* 筛选栏 */
.filter-bar {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 999;
  background: white;
  
  .filter-list {
    display: flex;
    height: 100rpx;
    border-bottom: 1px solid #ddd;
    
    .filter-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      color: #212121;
      position: relative;
      
      &.active {
        color: #ff1e00;
      }
      
      .filter-arrow {
        width: 18rpx;
        height: 11rpx;
        margin-left: 8rpx;
        transition: transform 0.3s;
        
        &.rotate {
          transform: rotate(180deg);
        }
      }
      
      .filter-icon {
        width: 20rpx;
        height: 24rpx;
        margin-left: 8rpx;
      }
    }
  }
  
  .dropdown-panel {
    background: white;
    border-top: 1px solid #ddd;
    max-height: 500rpx;
    overflow-y: auto;
    
    .category-list, .area-list, .sort-list {
      .category-item, .area-item, .sort-item {
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 30rpx;
        border-bottom: 1px solid #ddd;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        &.active {
          color: #ff1e00;
        }
        
        .check-icon {
          width: 11rpx;
          height: 17rpx;
        }
      }
    }
    
    .screen-content {
      .screen-options {
        padding: 30rpx;
        display: flex;
        flex-wrap: wrap;
        
        .screen-option {
          width: 215rpx;
          height: 70rpx;
          line-height: 70rpx;
          text-align: center;
          border: 1px solid #444444;
          border-radius: 10rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          font-size: 30rpx;
          
          &:nth-child(3n) {
            margin-right: 0;
          }
          
          &.active {
            border-color: #ff1e00;
            color: #ff1e00;
          }
        }
      }
      
      .screen-buttons {
        display: flex;
        
        .reset-btn, .confirm-btn {
          flex: 1;
          height: 80rpx;
          line-height: 80rpx;
          text-align: center;
          font-size: 40rpx;
        }
        
        .reset-btn {
          background: #ccc;
          color: #333;
        }
        
        .confirm-btn {
          background: #ff1e00;
          color: white;
        }
      }
    }
  }
}

/* 遮罩层 */
.mask {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 998;
}

/* 商家列表 */
.merchant-list {
  
  .list-content {
    padding-bottom: 20rpx;
    
    .merchant-item {
      margin-bottom: 20rpx;
      background: white;
      border-top: 1px solid #ddd;
      
      .merchant-info {
        display: flex;
        padding: 30rpx;
        border-bottom: 1px solid #ddd;
        
        .merchant-logo {
          width: 132rpx;
          height: 132rpx;
          margin-right: 20rpx;
          
          .logo-img {
            width: 100%;
            height: 100%;
            border: 1px solid #ddd;
            border-radius: 8rpx;
          }
        }
        
        .merchant-details {
          flex: 1;
          
          .merchant-name {
            font-size: 32rpx;
            font-weight: 700;
            color: #212121;
            margin-bottom: 15rpx;
          }
          
          .merchant-rating {
            margin-bottom: 15rpx;
          }
          
          .merchant-address {
            font-size: 22rpx;
            color: #777777;
          }
        }
      }
      
      .goods-list {
        .goods-item {
          border-bottom: 1px solid #ddd;
          
          .goods-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20rpx 30rpx 0;
            
            .goods-name {
              flex: 1;
              font-size: 28rpx;
              color: #212121;
            }
            
            .goods-sold {
              font-size: 24rpx;
              color: #6e6e6e;
              
              .sold-num {
                color: #6e6e6e;
              }
            }
          }
          
          .goods-price-info {
            display: flex;
            padding: 10rpx 30rpx 20rpx;
            
            .goods-price {
              font-size: 26rpx;
              color: #ff1e00;
              width: 200rpx;
            }
            
            .goods-rebate {
              font-size: 26rpx;
              color: #6e6e6e;
              
              .rebate-price {
                color: #ff9600;
              }
            }
          }
        }
      }
      
      .view-more {
        height: 72rpx;
        line-height: 72rpx;
        background: white;
        font-size: 24rpx;
        color: #f00000;
        text-align: center;
        border-top: 1px solid #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .more-arrow {
          height: 19rpx;
          width: 19rpx;
          margin-left: 10rpx;
          transition: transform 0.3s;
          
          &.rotate {
            transform: rotate(180deg);
          }
        }
      }
      
      .no-goods {
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        color: #999;
        font-size: 26rpx;
        background: #f8f8f8;
        border-top: 1px solid #ddd;
      }
    }
    
    .loading {
      padding: 20rpx;
    }
    
    .empty-state {
      text-align: center;
      padding: 160rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .empty-icon {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
      }
      
      .empty-text {
        color: #666;
        font-size: 32rpx;
        line-height: 1.5;
        padding: 0 60rpx;
        margin-bottom: 16rpx;
      }
      
      .empty-tips {
        color: #999;
        font-size: 28rpx;
        line-height: 1.4;
        padding: 0 60rpx;
      }
    }
  }
}
</style>